<template>
    <div class="login">
        <van-tabs v-model:active="active">

            <!-- 登录组件 -->
            <van-tab title="登录" animated="false">&nbsp;
                <van-form :onsubmit="loginTrue">
                    <van-cell-group inset>
                        <van-field v-model="username" name="用户名" label="用户名"
                            :rules="[{ required: true, message: '请填写姓名' }]" />

                        <van-field v-model="password" type="password" label="密码"
                            :rules="[{ required: true, message: '请输入您的密码' }]" />
                    </van-cell-group>
                    <div style="margin: 16px;">
                        <van-button round block type="primary" native-type="submit">
                            登录
                        </van-button>
                    </div>
                </van-form> &nbsp;
            </van-tab>

            <!-- 病人注册组件 -->
            <van-tab title="注册" color="red" animated="true">&nbsp;
                <van-form @submit="submitForm">
                    <van-cell-group inset>

                        <!-- 用户名 -->
                        <van-field v-model="user" label="用户名" placeholder="用于登录"
                            :rules="[{ required: true, message: '请填写用户名' }]" />
                        <!-- 电话 -->
                        <van-field v-model="phonenumber" type="number" label="电话" maxlength="11"
                            :rules="[{ required: true, message: '请填写电话' }]" placeholder="请输入您的11位电话" />
                        <!-- 生日 -->
                        <van-field v-model="digit" type="text" label="生日" placeholder="例：1901-01-31"
                            :rules="[{ required: true, message: '请填写生日' }]" />
                        <!-- 性别 -->
                        <van-field v-model="number" type="text" label="性别" maxlength="1" placeholder="男 / 女"
                            :rules="[{ required: true, message: '请填写性别' }]" />
                        <!-- 姓名 -->
                        <van-field v-model="text" type="text" label="姓名" placeholder="仅支持2-10位中文"
                            :rules="[{ required: true, message: '请填写姓名' }]" />
                        <!-- 密码 -->
                        <van-field v-model="registerpwd" type="password" label="密码" placeholder="密码至少6位"
                            :rules="[{ required: true, message: '请填写密码' }]" />
                    </van-cell-group>
                    <div style="margin: 16px;">
                        <van-button round block type="primary" @click="registerTrue" native-type="submit">
                            注册
                        </van-button>

                    </div>
                </van-form>
            </van-tab>

        </van-tabs>


    </div>
</template>

<script setup lang='ts'>
import { ref, onUnmounted } from 'vue';
import router from '@/router'
import { Toast } from 'vant';
import { login } from '../../api/api'
import link from '../../api/service2'
import { useStore } from 'vuex'
import $bus from "../../config/eventBus";
// 加入页面隐藏Tabbar
$bus.emit("tabBarHide", false);

// 退出页面时显示tabbar
onUnmounted(() => {
    $bus.emit("tabBarHide", true);
})

const active = ref(0)

const store = useStore()
// 登录表单内容
const username = ref('')
const password = ref('')

//禁止页面滚动
document.body.style.overflow = 'hidden'

//基础登录验证
const loginTrue = async () => {

    if (username.value === '') {
        Toast.fail('请输入用户名');
        return
    } else if (username.value === 'admin' && password.value === 'admin') {
        Toast.loading({
            message: '加载中...',
            // 禁止点击
            forbidClick: true,
        });
        router.push('/user')
        return
    } else if (password.value.length < 6) {
        Toast.fail('密码错误');
        return
    }
    //登录请求验证
    else {
        const res = await login({ username: username.value, password: password.value })
        // console.log(res);
        if (res.data.code === 200) {
            localStorage.setItem("token", res.data.token)
            localStorage.setItem("loginStatus", "true")
            localStorage.setItem("userInfo", JSON.stringify(res.data.data.data[0]))

            store.commit("setUserInfo", res.data.data.data[0])
            // console.log(store.state.userInfo);

            // Toast.loading({
            //     message: '加载中...',
            //     // 禁止点击
            //     forbidClick: true,
            // });
            router.push('/user')

        } else {
            Toast.fail('账号或密码错误，请检查！')
        }
    }

}

//注册页面表单内容
let text = ref('')
let phonenumber = ref('')
let digit = ref('')
let number = ref('')
let user = ref('')
let registerpwd = ref('')
let sex = ref()
// 电话正则
let telreg = /^1[3-9]\d{9}$/
// 生日正则
let birthdayreg = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/
// 性别正则
let sexreg = /^男$|^女$/;
// 姓名验证
let namereg = /^[\u4e00-\u9fa5]{2,16}$/

//点击注册基础逻辑 (正则验证)
const registerTrue = () => {
    if (user.value == "") {
        Toast.fail('请输入用户名');
        return
    } else if (phonenumber.value == "") {
        Toast.fail('请输入电话号码');
        return
    } else if (!(telreg.test(phonenumber.value))) {
        Toast.fail("手机号码有误，请重填");
        return
    } else if (digit.value === '') {
        Toast.fail("请输入出生年月!");
        return
    }
    else if (!(birthdayreg.test(digit.value))) {
        Toast.fail("生日格式不正确，请按要求填写!");
        return
    } else if (number.value === '') {
        Toast.fail("请输入您的性别!");
        return
    }
    else if (!(sexreg.test(number.value))) {
        Toast.fail("性别格式不正确，请按要求填写!");
        return
    }
    else if (text.value == "") {
        Toast.fail('请输入姓名');
        return
    } else if (!(namereg.test(text.value))) {
        Toast.fail('请输入您的真实姓名');
        return
    } else if (registerpwd.value.length <= 6) {
        Toast.fail('密码不能小于6位');
        return
    }
    // active.value = 0
}

//发送注册网络请求
const submitForm = (formEl: any | undefined) => {
    number.value === "男" ? sex.value = 1 : (number.value === "女" ? sex.value = 0 : '')

    // 把要发送的数据拼装成一个对象
    let data = {
        name: text.value,
        phonenumber: phonenumber.value,
        birthday: digit.value,
        gender: sex.value,
        username: user.value,
        password: registerpwd.value
    }
    link("/user/register", "POST", data).then((res: any) => {
        // console.log(res);
        // console.log(res.data.code);
        if (res.data.code === 200) {
            Toast.success('注册成功,快快登录体验吧')
            text.value = ''
            phonenumber.value = ''
            digit.value = ''
            number.value = ''
            user.value = ''
            registerpwd.value = ''
            //注册成功切换登录界面
            active.value = 0
        } else {
            Toast.fail('注册失败')
        }
    });

}


</script>

<style scoped lang='scss'>
.login {
    // margin: 36px;
    // margin-top: 50%;
    background: url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.doubanio.com%2Fview%2Fgroup_topic%2Fl%2Fpublic%2Fp380016762.jpg&refer=http%3A%2F%2Fimg2.doubanio.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667963304&t=1366a06c8396f0140e2ca57f4f7e4036");

    h2 {

        font-size: 31px;
        color: #666;
        margin-top: 0;
        margin-bottom: 21px;
        display: inline;
        text-align: center;
    }
}

body,
html,
.login {
    height: 100vh;
    width: 100vw;
    padding-top: 40%;
}
</style>